package cn.itlaobing.eshop.web.servlet;

import cn.itlaobing.eshop.entity.MsgToken;
import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Ajax请求，使用POST发送
 */
@WebServlet("/msgSend")
public class MsgSendServlet extends HttpServlet {
    Logger logger=Logger.getLogger(MsgSendServlet.class);

    public static final String MSG_TOKEN_IN_SESSION="MSG_TOKEN_IN_SESSION";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取手机号码
        String phone=req.getParameter("phone");
        //TODO 有效性验证
        HttpSession session = req.getSession();
        MsgToken msgToken=(MsgToken)session.getAttribute(MSG_TOKEN_IN_SESSION);

        if(msgToken!=null){//已经存在
            long diff=System.currentTimeMillis()-msgToken.getCrateAt();
            if(diff<60*1000){
                //错误，不允许发送短信验证码
                Map<String,Object> result= new HashMap<>();
                result.put("success",false);
                result.put("msg","验证码已发送");
                //  {"error":true,"msg":"验证码已发送"}
                resp.setContentType("application/json;charset=utf-8");
                resp.getWriter().write(JSON.toJSONString(result));
                return;
            }
        }

        msgToken=new MsgToken();
        msgToken.setCrateAt(System.currentTimeMillis());
        msgToken.setPhone(phone);
        String msgCode=genMsgCode();
        msgToken.setMsgCode(msgCode);
        logger.info("短信验证码："+msgCode);
        session.setAttribute(MSG_TOKEN_IN_SESSION,msgToken);
        Map<String,Object> result= new HashMap<>();
        result.put("success",true);
        result.put("msg","验证码已发送");
        //  {"error":true,"msg":"验证码已发送"}
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSON.toJSONString(result));

    }


    private String genMsgCode(){
        String number="0123456789";
        Random r=new Random(System.currentTimeMillis());
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<6;i++){
            int index=r.nextInt(number.length());
            sb.append(number.charAt(index));
        }
        return sb.toString();
    }
}
